<template>
<div>

<!-- 面包屑 -->
    <el-breadcrumb  separator-class="el-icon-arrow-right" >
    <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
    <el-breadcrumb-item>权限管理</el-breadcrumb-item>
    <el-breadcrumb-item>权限列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- el crad -->
    <el-card>
                <el-alert type="warning" title="只允许设置三级分类的相关操作" :closable="false" show-icon></el-alert>
        <el-row class="cat_opt">
            <el-col>
                <span>选择商品分类: </span>
                <!-- 级联选择框 -->
           <el-cascader expand-trigger="hover" v-model="selectCateKeys" :options="catelist" :props="cascaderProps"
    @change="handleChange"></el-cascader>
            </el-col>
        </el-row>
            <!-- tabs页签区 -->
      <el-tabs v-model="activeName" @tab-click="elclick">
    <el-tab-pane label="动态参数" name="many">
        <el-button type="primary" size="mini" :disabled="btndisable" @click="addDialog = true">添加参数</el-button>
        <!-- 动态表格 -->
        <el-table :data="manyData" border stripe>
            <!-- 在表格最前端添加下拉列 expand -->
            <el-table-column type="expand">
                <template slot-scope="scope">
                <el-tag v-for="(item,i) in scope.row.attr_vals" :key = "i" closable @close="handleClosd(i,scope.row)">{{item}}</el-tag>
                </el-tag>
                <!-- el-tag添加框的 -->
                <el-input
                class="input-new-tag"
                v-if="scope.row.inputVisible" 
                v-model="scope.row.inputValue"
                ref="saveTagInput"
                size="small"
                @keyup.enter.native="handleInputConfirm(scope.row)"
                @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>

                </template>
            </el-table-column>
            <!-- 绘制索引列 -->
            <el-table-column type="index">
            </el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
                <template slot-scope="scope">
                    <el-button type="primary" icon="el-icon-edit" size="mini" @click ="ShowEditDialog(scope.row.attr_id)">编辑</el-button>
                    <el-button type="danger" icon="el-icon-delete" size="mini" @click="RemoveEdit(scope.row.attr_id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        </el-tab-pane>
    
    <el-tab-pane label="静态属性" name="only">
        <el-button type="primary" size="mini" :disabled="btndisable"  @click="addDialog = true">添加属性</el-button>
        <!-- 静态属性列表 -->
            <el-table :data="onlyData" border stripe>
            <!-- 在表格最前端添加下拉列 expand -->
            <el-table-column type="expand">
                <template slot-scope="scope">
                <el-tag v-for="(item,i) in scope.row.attr_vals" :key = "i" closable @close="handleClosd(i,scope.row)">{{item}}</el-tag>
                </el-tag>
                <!-- el-tag添加框的 -->
                <el-input
                class="input-new-tag" v-if="scope.row.inputVisible"  v-model="scope.row.inputValue"
                ref="saveTagInput"
                size="small"
                @keyup.enter.native="handleInputConfirm(scope.row)"
                @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>

                </template>
            </el-table-column>
            <!-- 绘制索引列 -->
            <el-table-column type="index">
            </el-table-column>
            <el-table-column label="属性名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
                <template slot-scope="scope">
                    <el-button type="primary" icon="el-icon-edit" size="mini" @click ="ShowEditDialog(scope.row.attr_id)">编辑</el-button>
                    <el-button type="danger" icon="el-icon-delete" size="mini" @click="RemoveEdit(scope.row.attr_id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        </el-tab-pane>
    </el-tabs>

            <!-- 添加dialog对话框显示 -->
        <el-dialog
        :title="'添加' + chooseTitle"
        :visible.sync="addDialog"
        width="50%" @close="DialogClosed">
            <!-- 带验证的表单 -->
             <el-form :model="AddForm" :rules="AddFormRes" ref="AddFormRef" label-width="100px" >  
                 <el-form-item :label="chooseTitle" prop="attr_name">
                     <el-input v-model="AddForm.attr_name"></el-input></el-form-item>
             </el-form>
        
        <span slot="footer" class="dialog-footer">

            <el-button @click="addDialog = false">取 消</el-button>
            <el-button type="primary" @click="AddParams">确 定</el-button>
        </span>
        </el-dialog>

        <!-- 编辑的对话框 -->
                <el-dialog
        :title="'修改' + chooseTitle"
        :visible.sync="EditDialog"
        width="50%" @close="EditDialogClosed">
            <!-- 带验证的表单 -->
             <el-form :model="EditForm" :rules="EditFormRes" ref="EditFormRef" label-width="100px" >  
                 <el-form-item :label="chooseTitle" prop="attr_name">
                     <el-input v-model="EditForm.attr_name"></el-input></el-form-item>
             </el-form>
        
        <span slot="footer" class="dialog-footer">

            <el-button @click="EditDialog = false">取 消</el-button>
            <el-button type="primary" @click="EditParams">确 定</el-button>
        </span>
        </el-dialog>
    </el-card>
  
</div>
</template>

<script>
export default {
    data(){
        return {
            catelist:[],
            // 级联选择器配置对象
            cascaderProps:{
                value:'cat_id',
                label:'cat_name',
                children:'children'
            },
            // 级联选择器绑定获取到的值
            selectCateKeys:[],
            // el-tabs绑定的值
            activeName:'many',
            manyData:[],
            onlyData:[],
            // 显示dialog对话框 
            addDialog:false,
            // 数据对象
            AddForm:{
                attr_name:''
            },
            // 验证对象规则
            AddFormRes:{
                attr_name:[{required:true,message:'请输入',trigger:'blur'}]
            },
            // EditDialogVisble控制编辑窗口显示
            EditDialog:false,
            // EditForm数据
            EditForm:{
                
            },
            // EditForm校验规则
            EditFormRes:{
                attr_name:[{required:true,message:'请输入',trigger:'blur'}]
            },
            // tag添加框的状态
            inputVisible:false,
            // tag添加框数据
            inputValue:'',
        }
    },
    created(){
        // 获取数据列表
        this.getcatelist()

    },
    computed:{
        btndisable(){
            if(this.selectCateKeys.length !== 3){
                return true
            }
            return false
        },
        // 获取三级分类ID
        cateID(){
            if(this.selectCateKeys.length === 3){
                return this.selectCateKeys[2]
            }
            return null
        },

        // 显示dialog对话框
        addDialogVisble(){
            this.addDialog = true
        },
        // title显示修改
        chooseTitle(){
            if(this.activeName == "many"){
                return '动态参数'
            }else{
                return '静态属性'
            }
        }



    },
    methods:{
        // 获取数据列表
        async getcatelist(){
          const {data:res} = await this.$http.get('categories/')
          if(res.meta.status !== 200){
              return this.$message.error('获取失败')
          }
          this.catelist =res.data

        },
        // 级联选择器获取到改变值
         handleChange(){
             this.getParamsdata()
        },

        // el-tabs点击事件
        elclick(ee){
            console.log(ee.name);
            this.getParamsdata()

        },
       async getParamsdata(){
            

            if(this.selectCateKeys.length !== 3){
                this.selectCateKeys = []
                this.manyData = []
                this.onlyData = []
                return
            }
            
            // this.selectCateKeys = event
            // 向服务器请求参数
        const { data: res } = await this.$http.get(
        `categories/${this.cateID}/attributes`,
        {
          params: { sel: this.activeName }
        }
      )
            if(res.meta.status !== 200){
                return this.$message.error('获取数据失败')
            }
            // 气泡标签的实现,判断attr_vals是否为True
            res.data.forEach(item =>{
                item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') :[]
                // 创建每个对象的单独属性,控制Tag文本框
                item.inputVisible = false
                item.inputValue = ''

            })
            
            
            console.log(res.data);

            // 判断获取到的数据是否都点击的相同
            if(this.activeName == 'many'){
                this.manyData = res.data
                
            }else{
                this.onlyData = res.data
            }
        },
        // 监听添加框的关闭事件
        DialogClosed(){
            this.$refs.AddFormRef.resetFields()
        },
        // 创建提交数据按钮
        AddParams(){
            this.$refs.AddFormRef.validate(async valid => {
                if(!valid) return
               const {data : res}= await this.$http.post(`categories/${this.cateID}/attributes`,{
                    attr_name:this.AddForm.attr_name,
                    attr_sel:this.activeName
                })
                if(res.meta.status !== 201){
                   return this.$message.error('提交失败')
                }
                this.$message.success('提交成功')
                this.addDialog = false
                this.getParamsdata()
            })
        },
        // 显示Eidt对话框
        async ShowEditDialog(attr_id){
            // 获取服务器数据
           const {data : res} =await this.$http.get(`categories/${this.cateID}/attributes/${attr_id}`,{param:{
                attr_sel:this.activeName
            }})
            if(res.meta.status !== 200) return this.$message.error('查询失败')
            this.EditForm = res.data
            this.EditDialog = true

        },


        // 编辑清空表单函数
        EditDialogClosed(){
            this.$refs.EditFormRef.resetFields()
        },
        // EditParams
        EditParams(){
            this.$refs.EditFormRef.validate( async valid =>{
                if(!valid) return this.$message.error('修改失败!')
               const {data: res} = await this.$http.put(`categories/${this.cateID}/attributes/${this.EditForm.attr_id}`,{
                        attr_name:this.EditForm.attr_name,
                        attr_sel:this.activeName
                    
                })
                if(res.meta.status !== 200) return this.$message.error('请求失败')
                this.$message.success('修改成功')
                this.getParamsdata()
                this.EditDialog = false
            })
        },
        // 删除属性函数
        async RemoveEdit(attr_id){
           const confirmResulf = await this.$confirm('你是否删除当前属性',`提示`,{
                confirmButtonText:'确定',
                cancelButtonText:'取消',
                type:'warning'
            }).catch(err => err)
            // 取消
            if(confirmResulf !== 'confirm'){
                return this.$message.info('取消删除')
            }
            //确定
           const {data : res} = await this.$http.delete(`categories/${this.cateID}/attributes/${attr_id}`)
           if(res.meta.status !== 200){
              return this.$message.error('删除失败')
           }this.$message.success('删除成功')
           this.getParamsdata()
        },

        // 显示Tag文本框
        showInput(row){
            row.inputVisible = true
                // 点击input自动激活Focus
            this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        })
        },
        // Tag文本框失焦点时
        handleInputConfirm(row){
            if(row.inputValue.trim().length === 0 ){
                row.inputValue = ''
            row.inputVisible = false
                return
            }
            //  修整数组,储存数据
            row.attr_vals.push(row.inputValue.trim())
            // 清空输入框
            row.inputValue = ''
            row.inputVisible = false
            this.SaveVals(row)

        
        },
        
        // Tag关闭事件
        handleClosd(i,row){
            row.attr_vals.splice(i,1)
            this.SaveVals(row)


        },
        // 修改Atti_vals,并提交数据
       async SaveVals(row){
               const { data : res} = await this.$http.put(`categories/${this.cateID}/attributes/${row.attr_id}`,{
                attr_name:row.attr_name,
                attr_sel:row.attr_sel,
                attr_vals:row.attr_vals.join(' ')
            })
            if(res.meta.status !== 200) return this.$message.error('提交失')
            this.$message.success('提交成功')

        }


    }

}
</script>

<style lang="less" scoped>
.cat_opt{
    margin: 15px 0;
}
.el-tag{
    margin:10px;

}
.input-new-tag {
    width: 150px;
}
</style>